"""
项目相关功能
"""
import json
import sys
from tools import *
from project_info import *
from tab_func import *
from tab_query import *
from ctl_page import *
from sys_config import *
from tkinter import *

class SysProject():
    def __init__(self):
        self.menufile = 'menu.json'
        self.tools    = Tools()
        self.tab_func = TabFunc()
        self.project_info    = ProjectInfo().conf()
        self.config = SysConfig()
        self.config.init()

    def load_menu(self, win):
        """加载菜单
        """
        if self.tools.file_exist(self.menufile, True) == False:
            return False
        
        with open(self.menufile, 'r', encoding='utf-8') as f:
            try:
                self.data = json.load(f)
            except json.decoder.JSONDecodeError as e:
                self.tools.msg(f"加载菜单时发生错误:{e}", 'error')
                return False
            
        font_size = self.config.value('ui', 'font_size', 12)
        bar = Menu(win, font=('宋体', font_size))
        for m in self.data['menu']:
            sub_menu = Menu(win, font=('宋体', font_size))
            for item in m['items']:
                if item['caption'] == '-':
                    sub_menu.add_separator()
                else:
                    sub_menu.add_command(label=item['caption'], command = lambda item_key=item['key']: self.on_menu_click(item_key))

            bar.add_cascade(label=m['caption'], menu=sub_menu)

        win.config(menu=bar)
        self.parent = win

        return True
        
    def show_about(self):
        """显示关于窗口
        """
        s = f"""{self.project_info['name']}
版本:{self.project_info['version']}
最后更新:{self.project_info['last_update']}
python版本:{sys.version}
平台:{sys.platform}"""
        
        self.tools.msg(s, 'info')

    def get_char_width(self):
        """取得一个字符的像素宽度
        """
        ret = 0       
        children = self.parent.winfo_children()
        # 遍历子组件
        for child in children:
            print(f"{__name__}-get_char_width", type(child))
            if isinstance(child, Frame):
                print(f"{__name__}-get_char_width", '是 Frame')
                fc = child.winfo_children()
                print(f"{__name__}-get_char_width", 'Frame sub items len:', len(fc))
                # 遍历 Frame 的子组件
                for c in fc:
                    if isinstance(c, tk.Label):
                        label_width = c.winfo_width()
                        print(c['text'], c['width'], label_width)
                        ret = (label_width - c['borderwidth'] * 2) / c['width']
                        break
                break

        return ret
    
    def on_menu_click(self, item_key):
        """菜单事件
        """
        print(f"{__name__}-on_menu_click", item_key)
        # 系统功能
        if item_key == 'exit':
            self.parent.destroy()
        if item_key == 'sys_about':
            self.show_about()
        
        # 业务功能
        if item_key == 'page_man':
            # w = self.get_char_width()
            # print("计算平均字符宽度", w)
            ctrl = CtrlPage()
            tq = TabQuery(self.parent, ctrl, 'add,delete', '', 2) # ,edit,output,input,print


        if item_key == 'test':
            print(f"{__name__}-test get_size_desc", self.tab_func.get_size_desc(1220034500,'file:'))
            print(f"{__name__}-test sec_to_time", self.tab_func.sec_to_time(12300,'h时m分s秒'))